package com.forum.demo.services.impl;

import ch.qos.logback.core.util.StringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.forum.demo.common.ResultCode;
import com.forum.demo.mapper.ArticleMapper;
import com.forum.demo.model.Article;
import com.forum.demo.model.Board;
import com.forum.demo.model.response.ArticleResponse;
import com.forum.demo.services.IArticleService;
import com.forum.demo.utils.checkFailUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ArticleServiceImpl implements IArticleService {

    @Resource
    private ArticleMapper articleMapper;
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private BoardServiceImpl boardService;

    @Override
    public void create(Article article) {
        // 1. 非空校验
        if (article == null || article.getUserId() == null || article.getBoardId() == null
                || StringUtil.isNullOrEmpty(article.getTitle())
                || StringUtil.isNullOrEmpty(article.getContent())) {
            checkFailUtils.checkFail(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        // 2. 设置默认值
        article.setVisitCount(0); // 访问数
        article.setReplyCount(0); // 回复数
        article.setLikeCount(0);  // 点赞数
        article.setDeleteState((byte) 0);
        article.setState((byte) 0);
        Date date = new Date();
        article.setCreateTime(date);
        article.setUpdateTime(date);
        // 3. 存入数据库
        int row = articleMapper.insert(article);
        if (row != 1) {
            checkFailUtils.checkFail(ResultCode.FAILED_CREATE);
        }

        // 4. 修改用户帖子数
        userService.addOneArticleCountById(article.getUserId());
        // 5. 修改板块数
        boardService.addOneArticleCountById(article.getBoardId());
        // 打印日志
        log.info(ResultCode.SUCCESS.toString() + ", user id = " + article.getUserId()
                + ", board id = " + article.getBoardId() + ", article id = "+article.getId() + "发帖成功");
    }

    @Override
    public List<ArticleResponse> selectAll() {
        List<ArticleResponse> articles = articleMapper.selectArticleAndUser();
        if (articles == null) {
            articles = new ArrayList<>();
        }
        return articles;
    }

    @Override
    public List<ArticleResponse> selectAllByBoardId(Long boardId) {
        if (boardId == null || boardId <= 0) {
            checkFailUtils.checkFail(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        Board board = boardService.selectById(boardId);
        if (board == null) {
            checkFailUtils.checkFail(ResultCode.FAILED_BOARD_NOT_EXISTS);
        }
        List<ArticleResponse> articles = articleMapper.selectArticleAndUserByBoardId(boardId);
        if (articles == null) {
            articles = new ArrayList<>();
        }
        return articles;
    }

    @Override
    public List<Article> selectByUserId(Long userId) {
        if (userId == null) {
            checkFailUtils.checkFail(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        List<Article> articles = articleMapper.selectList(new LambdaQueryWrapper<Article>()
                .eq(Article::getDeleteState, 0)
                .eq(Article::getUserId, userId));
        return articles;
    }

    @Override
    public ArticleResponse selectDetailById(Long id) {
        if (id == null || id <= 0) {
            checkFailUtils.checkFail(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        Article article = articleMapper.selectById(id);
        if (article == null || article.getDeleteState() == 1) {
            checkFailUtils.checkFail(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }

        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setVisitCount(article.getVisitCount() + 1);
        // 更新帖子的访问数
        int row = articleMapper.update(updateArticle, new LambdaQueryWrapper<Article>().eq(Article::getId, id));
        if (row != 1) {
            checkFailUtils.checkFail(ResultCode.ERROR_SERVICES);
        }

        ArticleResponse articleResponse = articleMapper.selectArticleAndUserByArticleId(id);
        // 前端展示时与数据库匹配
        articleResponse.setVisitCount(article.getVisitCount() + 1);
        return articleResponse;
    }

    @Override
    public Article selectById(Long id) {
        if (id == null || id <= 0) {
            checkFailUtils.checkFail(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        Article article = articleMapper.selectById(id);
        return article;
    }

    @Override
    public void modify(Long id, String title, String content) {
        if (id == null || id <= 0 || StringUtil.isNullOrEmpty(title) || StringUtil.isNullOrEmpty(content)) {
            checkFailUtils.checkFail(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        Article updateArticle = new Article();
        updateArticle.setId(id); // id
        updateArticle.setTitle(title); // 标题
        updateArticle.setContent(content); // 正文
        updateArticle.setUpdateTime(new Date()); // 更新时间
        int row = articleMapper.update(updateArticle,new LambdaQueryWrapper<Article>().eq(Article::getId,id));
        if (row != 1) {
            checkFailUtils.checkFail(ResultCode.ERROR_SERVICES);
        }
    }

    @Override
    public void thumbsUpById(Long id) {
        if (id == null) {
            checkFailUtils.checkFail(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        Article article = articleMapper.selectById(id);
        // 帖子不存在
        if (article == null || article.getDeleteState() == 1) {
            checkFailUtils.checkFail(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        // 帖子状态异常
        if (article.getState() == 1) {
            checkFailUtils.checkFail(ResultCode.FAILED_ARTICLE_BANNED);
        }
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setLikeCount(article.getLikeCount() + 1);
        updateArticle.setUpdateTime(new Date());
        int row = articleMapper.update(updateArticle,new LambdaQueryWrapper<Article>().eq(Article::getId,id));
        if (row != 1) {
            checkFailUtils.checkFail(ResultCode.ERROR_SERVICES);
        }
    }

    @Override
    public void deleteById(Long id) {
        if (id == null) {
            checkFailUtils.checkFail(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        Article article = articleMapper.selectById(id);
        // 帖子不存在
        if (article == null || article.getDeleteState() == 1) {
            checkFailUtils.checkFail(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        // 帖子状态异常
        if (article.getState() == 1) {
            checkFailUtils.checkFail(ResultCode.FAILED_ARTICLE_BANNED);
        }
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setDeleteState((byte) 1);
        updateArticle.setUpdateTime(new Date());
        // 删除帖子
        articleMapper.update(updateArticle,new LambdaQueryWrapper<Article>().eq(Article::getId,id));

        // 4. 修改用户帖子数
        userService.subOneArticleCountById(article.getUserId());
        // 5. 修改板块数
        boardService.subOneArticleCountById(article.getBoardId());
        // 打印日志
        log.info(ResultCode.SUCCESS.toString() + ", user id = " + article.getUserId()
                + ", board id = " + article.getBoardId() + ", article id = "+article.getId() + "删帖成功");
    }

    @Override
    public void addOneReplyCountById(Long id) {
        if (id == null) {
            checkFailUtils.checkFail(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        Article article = articleMapper.selectById(id);
        // 帖子不存在
        if (article == null || article.getDeleteState() == 1) {
            checkFailUtils.checkFail(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        // 帖子状态异常
        if (article.getState() == 1) {
            checkFailUtils.checkFail(ResultCode.FAILED_ARTICLE_BANNED);
        }
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setReplyCount(article.getReplyCount() + 1);
        updateArticle.setUpdateTime(new Date());
        articleMapper.update(updateArticle,new LambdaQueryWrapper<Article>().eq(Article::getId,id));
    }
}
